/*************************************************************************
	> File Name: echoserver.c
	> Author: chen
	> Mail: chen_tmacy@foxmail.com
	> Created Time: 2014年07月14日 星期一 13时25分52秒
 ************************************************************************/

#include<stdio.h>
#include"csapp.h"

void echo(int connectfd);

int main(int argc, char ** argv){
    int listenfd,connectfd,port,clientlen;

    struct sockaddr_in clientaddr;
    struct hostent * hp;
    char * haddrp = NULL;

    if(argc != 2){
        fprintf(stderr,"Usage :%s <port> \n",argv[0]);
        exit(-1);
    }

    port = atoi(argv[1]);

    listenfd = open_listenfd(port);

    while(1){
        clientlen = sizeof(clientaddr);
        connectfd = accept(listenfd,(SA *)&clientaddr,&clientlen);
        
        hp = gethostbyaddr((const char*) &clientaddr.sin_addr.s_addr,
                sizeof(clientaddr.sin_addr.s_addr),AF_INET);


        haddrp = inet_ntoa(clientaddr.sin_addr);

        printf("server connect to %s (%s) \n",hp->h_name,haddrp);
        
        echo(connectfd);
        close(connectfd);
    }
    exit(0);
}


void echo(int connectfd){
    size_t n;
    char buf[1024];
    rio_t rio;

    rio_readinitb(&rio,connectfd);
    while((n = rio_readlineb(&rio,buf,1024)) != 0){
        printf("server received %d bytes\n",n);
        rio_writen(connectfd,buf,n);
    }
}
